#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import optparse
import os
import re
import shutil
import sys

__author__ = "köntzä"
__date__ = "$Mar 26, 2009 22:52:18 PM$"
subtitleCounter = 0

#~ Walk input directory for required files recordings.
def processInputDir( inputDir, regexp, callback, * args ):
    pat = re.compile( regexp, re.I )
    for root, dirs, files in os.walk( inputDir ):
        #~ Find all files of interest.
        fileList = {}
        for applicant in files:
            if pat.search( applicant ) is not None:
                #~ Root contains the dir where file is.
                if root in fileList:
                    fileList[root].append( applicant )
                else:
                    fileList[root] = [applicant]
        #~ Pass data to the callback.
        if len( fileList ):
            callback( fileList, * args )

#~ Postprocess output directory for subtitles.
def postprocessSubtitles( outputDir ):
    # Store the current directory.
    curDir = os.getcwd()
    os.chdir( outputDir )
    # Find .idx/.sub files generated by ProjectX
    entries = os.listdir( "." )
    filelist = {}
    filelist[outputDir] = []
    for entry in entries:
        applicant = entry
        if applicant.lower().endswith( ".sup.idx" ):
            # IDX-file found, store it.
            filelist[outputDir].append( applicant )
    subtitleProcessor( filelist )
    # Restore to the original directory.
    os.chdir( curDir )

# Process found subtitles.
def subtitleProcessor( fileList ):
    subtitleCounter = 1
    for idxDir in fileList.keys():
        for idxFile in fileList[idxDir]:
            curDir = os.getcwd()
            os.chdir( idxDir )
            # Extract basename and check if a SUB-file with the same basename is found.
            basename, extension = os.path.splitext( os.path.split( idxFile )[1] )
            if os.path.exists( "%s.sub" % basename ):
                # Both found, copy files.
                subFound = "%s.sub" % basename
                shutil.copyfile( "%s.idx" % basename, "%02d-subs.idx" % subtitleCounter )
                shutil.copyfile( "%s.sub" % basename, "%02d-subs.sub" % subtitleCounter )
                subtitleCounter = subtitleCounter + 1
            os.chdir( curDir )

# Entry point.
if __name__ == "__main__":
    #~ Handle options.
    parser = optparse.OptionParser()
    parser.add_option( "-p", "--post-process-subs", dest = "subsDir",
                    help = "Post-processses subtitle files in the fiven directory and its subdirectories.", metavar = "DIR" )
    ( options, args ) = parser.parse_args()
    #~ Sanity checking.
    if options.subsDir is not None:
        processInputDir( options.subsDir, "\.sup\.idx", subtitleProcessor )
